package com.lagou.server;

import com.lagou.common.*;
import com.lagou.pojo.RpcRequest;
import com.lagou.pojo.RpcResponse;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.ExecutionException;

public class RpcClient {

    @Autowired
    RpcRegistryFactory rpcRegistryFactory;

    String nettyIp;
    int port;
    Channel channel;

    public RpcClient(String nettyIp, int port){
        this.nettyIp = nettyIp;
        this.port = port;
    }

    public void initClient(String serviceClassName) throws InterruptedException{
        // 创建连接池
        EventLoopGroup group = new NioEventLoopGroup();
        // 创建客户端启动
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // 获取管道对象
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcResponse.class, new JSONSerializer()));
                        pipeline.addLast(new UserClientHandler());
                    }
                });

        this.channel = bootstrap.connect(this.nettyIp, this.port).sync().channel();
        System.out.println("=====启动客户端：" + serviceClassName + ",ip" + nettyIp +",port" + port);
    }

    public Object send(RpcRequest request) throws InterruptedException, ExecutionException {
        RequestMetrics.getInstance().put(nettyIp, this.port,request.getRequestId());
        Void aVoid = this.channel.writeAndFlush(request).sync().get();
        RequestMetrics.getInstance().calculate(request.getRequestId());
        return aVoid;
    }

    public String getNettyIp() {
        return nettyIp;
    }

    public void setNettyIp(String nettyIp) {
        this.nettyIp = nettyIp;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}
